/// Wiki配置数据模型
/// Wiki configuration data models

/// Wiki配置主类
class WikiConfig {
  final String version;
  final DateTime lastUpdated;
  final List<WikiItem> wikis;
  final List<WikiCategory> categories;
  final WikiFeatures features;

  WikiConfig({
    required this.version,
    required this.lastUpdated,
    required this.wikis,
    required this.categories,
    required this.features,
  });

  factory WikiConfig.fromJson(Map<String, dynamic> json) {
    return WikiConfig(
      version: json['version'] ?? '1.0.0',
      lastUpdated: DateTime.parse(json['lastUpdated'] ?? DateTime.now().toIso8601String()),
      wikis: (json['wikis'] as List<dynamic>? ?? [])
          .map((item) => WikiItem.fromJson(item))
          .toList(),
      categories: (json['categories'] as List<dynamic>? ?? [])
          .map((item) => WikiCategory.fromJson(item))
          .toList(),
      features: WikiFeatures.fromJson(json['features'] ?? {}),
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'version': version,
      'lastUpdated': lastUpdated.toIso8601String(),
      'wikis': wikis.map((item) => item.toJson()).toList(),
      'categories': categories.map((item) => item.toJson()).toList(),
      'features': features.toJson(),
    };
  }
}

/// Wiki项目模型
class WikiItem {
  final String id;
  final String name;
  final String nameEn;
  final String nameCn;
  final String description;
  final String descriptionCn;
  final String url;
  final String urlCn;
  final String icon;
  final String category;
  final List<String> tags;
  final bool isPopular;
  final bool isOfficial;
  final List<String> language;
  final double rating;
  final DateTime lastUpdated;
  final DateTime? visitTime;

  WikiItem({
    required this.id,
    required this.name,
    required this.nameEn,
    required this.nameCn,
    required this.description,
    required this.descriptionCn,
    required this.url,
    required this.urlCn,
    required this.icon,
    required this.category,
    required this.tags,
    required this.isPopular,
    required this.isOfficial,
    required this.language,
    required this.rating,
    required this.lastUpdated,
    this.visitTime,
  });

  factory WikiItem.fromJson(Map<String, dynamic> json) {
    return WikiItem(
      id: json['id'] ?? '',
      name: json['name'] ?? '',
      // 支持远程JSON的nameEn字段
      nameEn: json['nameEn'] ?? json['name'] ?? '',
      // 支持远程JSON的nameZh字段映射到nameCn
      nameCn: json['nameCn'] ?? json['nameZh'] ?? json['name'] ?? '',
      description: json['description'] ?? '',
      descriptionCn: json['descriptionCn'] ?? json['description'] ?? '',
      // 支持远程JSON的baseUrl字段映射到url
      url: json['url'] ?? json['baseUrl'] ?? '',
      urlCn: json['urlCn'] ?? json['baseUrl'] ?? json['url'] ?? '',
      // 支持远程JSON的iconUrl字段映射到icon
      icon: json['icon'] ?? json['iconUrl'] ?? '',
      category: json['category'] ?? 'other',
      // 支持远程JSON的searchKeywords字段映射到tags
      tags: List<String>.from(json['tags'] ?? json['searchKeywords'] ?? []),
      isPopular: json['isPopular'] ?? false,
      isOfficial: json['isOfficial'] ?? false,
      // 支持远程JSON的supportedLanguages字段映射到language
      language: List<String>.from(json['language'] ?? json['supportedLanguages'] ?? ['en']),
      rating: (json['rating'] ?? 0.0).toDouble(),
      // 处理可能缺失的lastUpdated字段
      lastUpdated: json['lastUpdated'] != null 
          ? DateTime.parse(json['lastUpdated']) 
          : DateTime.now(),
      visitTime: json['visitTime'] != null ? DateTime.parse(json['visitTime']) : null,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'nameEn': nameEn,
      'nameCn': nameCn,
      'description': description,
      'descriptionCn': descriptionCn,
      'url': url,
      'urlCn': urlCn,
      'icon': icon,
      'category': category,
      'tags': tags,
      'isPopular': isPopular,
      'isOfficial': isOfficial,
      'language': language,
      'rating': rating,
      'lastUpdated': lastUpdated.toIso8601String(),
      'visitTime': visitTime?.toIso8601String(),
    };
  }

  /// 获取本地化名称
  String getLocalizedName(String locale) {
    switch (locale) {
      case 'zh':
      case 'zh_CN':
        return nameCn.isNotEmpty ? nameCn : name;
      default:
        return nameEn.isNotEmpty ? nameEn : name;
    }
  }

  /// 获取本地化描述
  String getLocalizedDescription(String locale) {
    switch (locale) {
      case 'zh':
      case 'zh_CN':
        return descriptionCn.isNotEmpty ? descriptionCn : description;
      default:
        return description;
    }
  }

  /// 获取本地化URL
  String getLocalizedUrl(String locale) {
    switch (locale) {
      case 'zh':
      case 'zh_CN':
        return urlCn.isNotEmpty ? urlCn : url;
      default:
        return url;
    }
  }

  /// 检查是否匹配搜索关键词
  bool matchesSearch(String query, String locale) {
    final lowerQuery = query.toLowerCase();
    final localizedName = getLocalizedName(locale).toLowerCase();
    final localizedDesc = getLocalizedDescription(locale).toLowerCase();
    
    return localizedName.contains(lowerQuery) ||
           localizedDesc.contains(lowerQuery) ||
           name.toLowerCase().contains(lowerQuery) ||
           nameEn.toLowerCase().contains(lowerQuery) ||
           nameCn.toLowerCase().contains(lowerQuery) ||
           tags.any((tag) => tag.toLowerCase().contains(lowerQuery));
  }
}

/// Wiki分类模型
class WikiCategory {
  final String id;
  final String name;
  final String nameCn;
  final String description;
  final String descriptionCn;
  final String icon;
  final String color;

  WikiCategory({
    required this.id,
    required this.name,
    required this.nameCn,
    required this.description,
    required this.descriptionCn,
    required this.icon,
    required this.color,
  });

  factory WikiCategory.fromJson(Map<String, dynamic> json) {
    return WikiCategory(
      id: json['id'] ?? '',
      // 支持远程JSON的nameEn字段，优先使用name字段
      name: json['name'] ?? json['nameEn'] ?? '',
      // 支持远程JSON的nameEn字段映射，如果没有nameCn则使用name
      nameCn: json['nameCn'] ?? json['name'] ?? json['nameEn'] ?? '',
      description: json['description'] ?? '',
      descriptionCn: json['descriptionCn'] ?? json['description'] ?? '',
      icon: json['icon'] ?? '',
      color: json['color'] ?? '#2196F3',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'nameCn': nameCn,
      'description': description,
      'descriptionCn': descriptionCn,
      'icon': icon,
      'color': color,
    };
  }

  /// 获取本地化名称
  String getLocalizedName(String locale) {
    switch (locale) {
      case 'zh':
      case 'zh_CN':
        return nameCn.isNotEmpty ? nameCn : name;
      default:
        return name;
    }
  }

  /// 获取本地化描述
  String getLocalizedDescription(String locale) {
    switch (locale) {
      case 'zh':
      case 'zh_CN':
        return descriptionCn.isNotEmpty ? descriptionCn : description;
      default:
        return description;
    }
  }
}

/// Wiki功能配置
class WikiFeatures {
  final bool searchEnabled;
  final bool favoritesEnabled;
  final bool historyEnabled;
  final bool offlineEnabled;
  final bool darkModeEnabled;
  final bool multiLanguageEnabled;

  WikiFeatures({
    required this.searchEnabled,
    required this.favoritesEnabled,
    required this.historyEnabled,
    required this.offlineEnabled,
    required this.darkModeEnabled,
    required this.multiLanguageEnabled,
  });

  factory WikiFeatures.fromJson(Map<String, dynamic> json) {
    return WikiFeatures(
      searchEnabled: json['searchEnabled'] ?? true,
      favoritesEnabled: json['favoritesEnabled'] ?? true,
      historyEnabled: json['historyEnabled'] ?? true,
      offlineEnabled: json['offlineEnabled'] ?? false,
      darkModeEnabled: json['darkModeEnabled'] ?? true,
      multiLanguageEnabled: json['multiLanguageEnabled'] ?? true,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'searchEnabled': searchEnabled,
      'favoritesEnabled': favoritesEnabled,
      'historyEnabled': historyEnabled,
      'offlineEnabled': offlineEnabled,
      'darkModeEnabled': darkModeEnabled,
      'multiLanguageEnabled': multiLanguageEnabled,
    };
  }
}

/// 搜索结果模型
class WikiSearchResult {
  final WikiItem wiki;
  final double relevance;
  final List<String> matchedFields;

  WikiSearchResult({
    required this.wiki,
    required this.relevance,
    required this.matchedFields,
  });
}

/// 搜索过滤器
class WikiSearchFilter {
  final String? category;
  final List<String>? tags;
  final bool? isPopular;
  final bool? isOfficial;
  final List<String>? languages;
  final double? minRating;

  WikiSearchFilter({
    this.category,
    this.tags,
    this.isPopular,
    this.isOfficial,
    this.languages,
    this.minRating,
  });

  /// 检查Wiki项目是否匹配过滤器
  bool matches(WikiItem wiki) {
    if (category != null && wiki.category != category) {
      return false;
    }

    if (tags != null && tags!.isNotEmpty) {
      final hasMatchingTag = tags!.any((tag) => wiki.tags.contains(tag));
      if (!hasMatchingTag) return false;
    }

    if (isPopular != null && wiki.isPopular != isPopular) {
      return false;
    }

    if (isOfficial != null && wiki.isOfficial != isOfficial) {
      return false;
    }

    if (languages != null && languages!.isNotEmpty) {
      final hasMatchingLanguage = languages!.any((lang) => wiki.language.contains(lang));
      if (!hasMatchingLanguage) return false;
    }

    if (minRating != null && wiki.rating < minRating!) {
      return false;
    }

    return true;
  }
}